package mweb

import (
	"embed"
	"gitee.com/dennis-mxx/mxx-core-v2/mlogger"
	"gitee.com/dennis-mxx/mxx-core-v2/mutil"
	"github.com/gin-gonic/gin"
	"strings"
)

type RedirectFileServer struct {
	FS      embed.FS
	Dir     string
	Ignore  []string
	Adapter func(ctx *gin.Context) bool
}

func (ew RedirectFileServer) Create() func(ctx *gin.Context) {

	return func(ctx *gin.Context) {
		uri := ctx.Request.URL.Path
		static := true
		for _, item := range ew.Ignore {
			if strings.HasPrefix(uri, item) {
				static = false
				ctx.Next()
				return
			}
		}
		if static {
			if ew.Adapter == nil || ew.Adapter(ctx) {
				var contentType string
				var b []byte
				var e error
				if paths := strings.Split(uri, "/"); len(paths) > 0 {
					filename := paths[len(paths)-1]
					i := strings.LastIndexAny(filename, ".")
					if i > 0 {
						suffix := filename[i:]
						contentType = mutil.Extension(suffix)
						b, e = ew.FS.ReadFile(ew.Dir + uri)
					} else {
						b, e = ew.FS.ReadFile(ew.Dir + "/index.html")
					}
				} else {
					b, e = ew.FS.ReadFile(ew.Dir + "/index.html")
				}
				if contentType == "" {
					contentType = "text/html;charset=utf-8"
				}
				ctx.Header("Content-Type", contentType)
				if e == nil {
					ctx.Status(200)
					if _, err := ctx.Writer.Write(b); err != nil {
						mlogger.Out.Error("file server writer exception", e)
					}
				} else {
					mlogger.Out.Error("file server reader exception", e)
				}
			}
		}
	}
}

func NewRedirectFileServer(fs embed.FS, prefix []string) func(ctx *gin.Context) {
	return RedirectFileServer{FS: fs, Ignore: prefix, Dir: "build", Adapter: func(ctx *gin.Context) bool {
		ctx.Header("Accept-Ranges", "bytes")
		ctx.Header("Connection", "keep-alive")
		ctx.Header("Keep-Alive", "timeout=5")
		ctx.Header("X-Powered-By", "Express")
		ctx.Header("Cache-Control", "max-age=1800")
		return true
	}}.Create()
}
